package com.book.controller;

import cn.hutool.captcha.LineCaptcha;
import com.book.entity.*;
import com.book.service.AccountInfoService;
import com.book.service.CartService;
import com.book.util.ResultBack;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * @program:
 * @ClassName:
 * @description:
 * @author: zgc
 * @date:
 * @Version 1.0
 **/
@Controller
@RequestMapping("/account")
public class AccountController {
    @Resource
    private AccountInfoService accountInfoService;
    @Resource
    LineCaptcha lineCaptcha;
    @Resource
    HashMap<String,String> map ;
    
    @Resource
    private CartService cartService;
    
    @RequestMapping("/toLogin")
    public String login() {
        return "login-new";
    }

    @RequestMapping("/toMain")
    public String main() {
        return "index";
    }
    
    @RequestMapping("/toExit")
    public String exit(HttpSession httpSession) {
        httpSession.invalidate();
        return "login-new";
    }

    @RequestMapping("/toCenter")
    public String toCenter() {
        return "center";
    }

    
    @RequestMapping("/validateAccount")
    @ResponseBody
    public ResultBack validateAccount(Account account,String code,String codeId, HttpSession httpSession) {
        System.out.println(account.getUserName());
        System.out.println(account.getPassword());
        Account result = accountInfoService.validateAccount(account);
        // 从缓存中得到codeId匹配的code进行验证
        String mapCode = map.get(codeId);
       if (mapCode != null && mapCode.equalsIgnoreCase(code)){
           if (result != null) {
               if (result.getPassword().equals(account.getPassword())) {
                   httpSession.setAttribute("account", result);
                   return ResultBack.success("登录成功", null);
               } else {
                   return ResultBack.failure("密码错误");
               }
           } else {
               return ResultBack.failure("账号错误");
           }
       }else {
           return ResultBack.failure("验证码有误");
       }
    }

    @PutMapping("/updateUserInfo")
    @ResponseBody
    public ResultBack updateUserInfoById(Account account, HttpSession session) throws Exception {
        Account account1 = (Account) session.getAttribute("account");
        Long userId = account1.getId();
        account.setId(userId);
        int i = accountInfoService.updateUserInfoById(account);
        if (i > 0) {
            return ResultBack.success("修改成功", i);
        } else {
            return ResultBack.failure("修改失败");
        }
    }

    

    
}
